<!-- 组织管理 -->
<template>
   <div class='organList'>
       <div class='organList_left'>
          <Tree :data="treeList" :render="renderContent" @on-select-change="treeChange" class="demo-tree-render"></Tree>
       </div>
       <div class='organList_right'>
         <list ref="list" :treeList="treeList" @getDepartmentList="getDepartmentList"></list>
       </div>
       <!-- 修改名称 -->
       <Modal v-model="changeNameModel" width="300" title="修改名称">
        <div>
          <span style="margin-right:10px">名称:</span>
          <Input v-model="changeName" placeholder="请填写名称" clearable style="width: 200px" />
        </div>
         <div slot="footer">
          <Button type="text" @click="changeNameModel = false">取消</Button>
          <Button type="primary" @click="changeNameSure()">确定</Button>
        </div>
     </Modal>
     <!-- 新增部门 -->
      <Modal v-model="addNameModel" width="500" title="新增部门" >
        <Form ref="addDepartment" :model="addDepartment" :rules="ruleValidate" :label-width="80">
            <FormItem label="部门名称" prop="orgName">
              <Input v-model="addDepartment.orgName" placeholder="请填写部门名称"></Input>
           </FormItem>
           <!-- <FormItem label="关联案场" prop="buildingIds">
            <Select v-model="addDepartment.buildingIds" multiple placeholder="请选择关联案场">
                <Option :value="item.buildingId" v-for="item in buildingList" :key="item. buildingId" >{{`${item.buildingAlias}(${item.provinceName}-${item.cityName})`}}</Option>
            </Select>
        </FormItem> -->
        </Form>
        <div slot="footer">
          <Button type="text" @click="addNameModel = false">取消</Button>
          <Button type="primary" @click="addCasen('addDepartment')">确定</Button>
        </div>
     </Modal>
   </div>
</template>

<script>
import list from "@/components/system_center/organ";
import { getDepartmentTree, getDepartmentAdd, getDepartmentUpdate, getDepartmentDelete} from '@/api/system_center';
import commonMixins from "@/common/constant/commonMixins"
export default {
  components:{list},
  mixins:[commonMixins],
  data () {
    const ruleValidateName = (rule, data, callback) =>{
        if(!data || data.length>15)return callback("请输入不超过15个字符长度的部门名称")
      callback()
    }
    return {
      treeList: [],
      buttonProps: {
          type: 'default',
          size: 'small',
      },
      changeNameModel:false,
      changeName:"",
      changeNameLoading:true,
      currentMess: {},
      addNameModel:false,
      addDepartment:{
        orgName:'',
        buildingIds:[]
      },
      ruleValidate:{
         orgName: [
           {validator:ruleValidateName ,trigger: 'blur' }
         ], 
      }

    }
  },
  created(){
    //获取部门列表
    this.getDepartmentList()
  },
  methods: {
     renderContent (h, { root, node, data }) {
        return h('span', {}, [
            h('span', [
                h('Icon', {
                    props: {type: 'ios-paper-outline'},
                    style: {marginRight: '8px',}
                }),
                h('span', data.title)
            ]),
            h('span', {style: {display: 'inline-block',float: 'right',},},
            [
                h('Button', {
                    props: Object.assign({}, this.buttonProps, {icon: 'md-add',}),
                    style: {marginRight: '8px',},
                    on: {click: (e) => { e.stopPropagation();;this.addBranch(data) },}
                }),
                h('Button', {
                    props: Object.assign({}, this.buttonProps, { icon: 'md-settings',}),
                     style: {marginRight: '8px',},
                    on: {click: (e) => {  e.stopPropagation();this.undateBranch(root, node, data, 'second') },}
                }),
                h('Button', {props: Object.assign({}, this.buttonProps, {icon: 'md-close',}),
                    on: {click: (e) => {  e.stopPropagation();this.deleteBranch(root, node, data) }, }
                })
            ])
        ]);
             
     },
     //获取部门列表
     getDepartmentList(){
        getDepartmentTree({delFlag:2}).then(res=>{
            console.log("部门列表",res);
            res.forEach(ms =>{
                ms.render = this.returnRender();
                ms.title = ms.orgName;
                ms.expand =  true;
                ms.children &&  this.forEachDepartment(ms.children);
            })
            this.treeList = res;
            res.length>0 && this.$refs.list.getmemberList({orgId:res[0].orgId})
        })
     },
     //循环遍历部门
     forEachDepartment(mess){
       mess.map(item=>{
           item.title = item.orgName;
           item.expand =  true;
           item.children && this.forEachDepartment(item.children)
       })
     },
     //添加部门
     addCasen(name){
        this.$refs[name].validate((valid) => {
           if (valid) {
             let { orgName, buildingIds} = this.addDepartment,
             {parentId, orgCode, orgId} = this.currentMess.data;
             let params = {
                 orgName,
                 buildingIds,
                 orgType:2,
                 parentId:orgId,
             }
              getDepartmentAdd(params).then(res=>{
                this.$Message.success(`${orgName}部门添加成功`)
                  this.getDepartmentList();
                 this.addNameModel = false;
                 this.$refs[name].resetFields();
              }).catch(res=>this.$Message.error(res))
              
           } 
        })
     },
    //  append (mess) {
    //      let { data } =  this.currentMess;
    //      const children = data.children || [];
    //      children.push(mess);
    //      this.$set(data, 'children', children);
    //  },
    //  remove (root, node, data) {
    //      const parentKey = root.find(el => el === node).parent;
    //      const parent = root.find(el => el.nodeKey === parentKey).node;
    //      const index = parent.children.indexOf(data);
    //      parent.children.splice(index, 1);
    //  },
    //  undate(mess){
    //      let { root, node, data } =  this.currentMess;
    //      const parentKey = root.find(el => el === node).parent;
    //      const parent = root.find(el => el.nodeKey === parentKey).node;
    //      const index = parent.children.indexOf(data);
    //      data.title = mess;
    //      parent.children.splice(index, 1,data);
    //  },
    //  undateMessFirst(mess){
    //      let { root, node, data } =  this.currentMess;
    //      data.title = mess;
    //      console.log(root, node, data)
    //  },
     addBranch(data){
         console.log(8585)
        this.getAllbuildingList({page:1,rows:100})
        this.currentMess.data = data;
        this.addDepartment = {};
        this.addNameModel = true;
     },
     undateBranch(root, node, data,type){
       this.currentMess.root = root;
       this.currentMess.node = node;
       this.currentMess.data = data;
       this.changeNameModel = true;
       this.changeNameType = type;  
      console.log(data)
     },
     deleteBranch(root, node, data){
       let { orgName, parentId,orgId} = data;
       let params = {
          orgId,
          delFlag:1,
       }
       getDepartmentDelete(params).then(res=>{
        console.log('删除结果',res);
        this.$Message.success("删除成功")
        //this.remove(root, node, data);
        this.getDepartmentList()
       }).catch(res=>{
         this.$Message.error(res)
       })
     },
     changeNameSure(){
        if(!this.changeName){
            this.$Message.error('请填写名称');
            this.changeNameLoading = false;
            return;
        };
        let {orgId} = this.currentMess.data;
        let params = {
            orgId,
            orgName:this.changeName, 
            orgType:this.changeNameType == "first"?'1':'2'
        };
        getDepartmentUpdate(params).then(res=>{
          this.$Message.success("部门名字修改成功")
          //this.changeNameType == "first"?this.undateMessFirst(this.changeName):this.undate(this.changeName);
          this.getDepartmentList()
         this.changeNameModel = false;
         this.changeName = "";
        })
         
     },
     returnRender(){
         return (h, { root, node, data }) => {
                     return h('span', {
                         style: {
                             display: 'inline-block',
                             width: '100%',
                         }
                     }, [
                         h('span', [
                             h('Icon', {
                                 props: {
                                     type: 'ios-folder-outline'
                                 },
                                 style: {
                                     marginRight: '8px',
                                 }
                             }),
                             h('span', data.title)
                              
                         ]),
                         h('span', {
                             style: {
                                 display: 'inline-block',
                                 float: 'right',
                             },
                         },
                         [
                             h('Button', {
                                 props: Object.assign({}, this.buttonProps, {
                                     icon: 'md-add',
                                     type: 'success'
                                 }),
                                 style: {
                                     marginRight: '8px',
                                 },
                                 on: {
                                     click: (e) => { e.stopPropagation(); this.addBranch(data) },
                                     
                                 }
                             }),
                             h('Button', {
                                 props: Object.assign({}, this.buttonProps, {
                                     icon: 'md-settings',
                                     type: 'warning'
                                 }),
                                 on: {
                                     click: (e) => { e.stopPropagation(); this.undateBranch(root, node, data,'first') },
                                 }
                             })
                         ])
                     ]);
      }
    },
    treeChange(event){
      this.$refs.list.getmemberList({orgId:event[0]?event[0].orgId:''})
    }
  }
}
</script>
<style lang='scss' scoped>
.organList{
  padding: 20px;
  height: 100%;
  width: 100%;
  display: flex;
  &_left{
    flex: 0 0 300px;
    height: 100%;
    border: 1px solid #ccc;
    margin-right: 20px;
    border-radius: 8px;
    max-height: 100%;
    overflow-y: auto;
  }
  &_right{
    flex:1;
    height: 100%;
    border: 1px solid #ccc;
    border-radius: 8px;
  }
  /deep/.ivu-tree-title{
        width: calc(100% - 15px);
  }
}
</style>